<template>
  <m-modal
    v-model="visible"
    title="保存图片"
    :width="500"
    :okLoading="okLoading"
    :center="true"
    @ok="submit"
    @cancel="handleCancel">
    <div class="v-save-image">
      <a-form
        :form="form" 
        :label-col="{ span: 5 }" 
        :wrapper-col="{ span: 14 }"
        :hideRequiredMark="hideRequiredMark">
        <a-form-item label="保存地址">
          <a-input
            v-decorator="['path', { rules: [{ required: true, message: '请选择保存路径!' }] }]"
            @change="handleInputChange"
          />
        </a-form-item>
        <a-form-item label="图片格式">
          <a-select
            :value="type"
            placeholder="请选择图片类型"
            @change="handleSelectChange"
          >
            <a-select-option value="jpg">
              JPG
            </a-select-option>
            <a-select-option value="pdf">
              PDF
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <a-button class="import-button" icon="ellipsis" @click="selectPath"></a-button>
    </div>
  </m-modal>
</template>
<script>
import { Portal } from 'src/components/common/Portal.vue';
import Modal from 'src/components/common/CustomModal';
import { WarningModal } from './WarningModal';
import LocalFile from 'src/util/localFile/index';

const comp = {
  name: 'comp-save-image',
  components: {
    'm-modal': Modal,
  },
  props: ['graph', 'graphContent'],
  data() {

    return {
      visible: false,
      hideRequiredMark: true,
      type: 'jpg',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      folderPath: '',
      okLoading: false,
      fileName: ''
    };
  },
  mounted() {
    this.visible = true;
    console.log('graph', this.graph);
    this.folderPath = window.process.cwd();
    const diagramName = this.graph.view.graph.diagramNode.name;
    const type = this.getTypeName(this.graph.view.graph.diagramType);
    this.fileName = type + '_' + diagramName;
    this.setFilePath();
  },

  methods: {
    handleOk() {
      this.visible = false;
      this.$emit('sure', );
    },
    handleCancel() {
      this.visible = false;
      this.$emit('close');
    },
    submit(overwrite) {
      this.form.validateFields((err, values) => {
        if (err) return false;
        this.okLoading = true;
        const filePath = window.$ele.path.resolve(this.folderPath, this.fileName + '.' + this.type);
        LocalFile.exportImage(filePath, this.graphContent, this.type, overwrite).then(() => {
          app.$messageBox.success({ text: '导出成功' });
          this.handleOk();
        }).catch(err => {
          if (err.text) {
            WarningModal.popup({ text: '文件已存在，是否替换？', title: '' }).then(() => {
              this.submit(true);
            });
            return;
          }
          app.$messageBox.error({ text: err });
        }).finally(() => {
          this.okLoading = false;
        });
      });
    },
    handleInputChange(e) {
      const value = e.target.value;
      this.folderPath = window.$ele.path.dirname(value);
      this.fileName = window.$ele.path.basename(value);
    },
    handleSelectChange(value) {
      //// const fileName = window.$ele.path.basename(this.fileName, '.' + this.type); //// 获取文件名，不包括扩展名
      //// this.fileName = fileName + '.' + value;
      this.type = value;
      this.setFilePath();
    },
    setFilePath() {
      const filePath = window.$ele.path.resolve(this.folderPath, this.fileName);
      this.form.setFieldsValue({
        path: filePath,
      });
    },
    selectPath() {
      //// const filePath = LocalFile.showSaveDialog({
      ////   defaultPath: window.$ele.path.resolve(this.folderPath, this.fileName),
      ////   filters: [{ name: 'jpg or pdf', extensions: [ this.type ] }]
      //// });
      const folderPath = LocalFile.showOpenDialog({
        defaultPath: window.$ele.path.resolve(this.folderPath),
        properties: ['openDirectory']
      });
      if (!folderPath) return;
      this.folderPath = folderPath;
      //// this.fileName = window.$ele.path.basename(filePath);
      this.setFilePath();
      //// console.log(filePath);
    },
    getTypeName(type) {
      console.log('type', type);
      switch (type) {
        case 'SysMLBlockDefinitionDiagram':
          return 'BDD';
        case 'SysMLPackageDiagram':
          return 'PKG';
        case 'SysMLRequirementDiagram':
          return 'REQ';
        case 'SysMLUseCaseDiagram':
          return 'UC';
        case 'SysMLInternalBlockDiagram':
          return 'IBD';
        case 'SysMLParametricDiagram':
          return 'PAR';
        case 'SysMLActivityDiagram':
          return 'ACT';
        case 'SysMLStateMachineDiagram':
          return 'STM';
        case 'SysMLSequenceDiagram':
          return 'SD';
        case 'RocketTD':
          return 'RKT';
        case 'SysMLProfileDiagram':
          return 'PFL';
        default:
          return '';
      }
    }
  }
};
export default comp;
export const saveImage = new Portal(comp, { single: true });
export const portal = saveImage;
</script>
<style lang="scss">
.v-save-image {
  position: relative;
  .ant-form {
    margin-top: 20px;
  }
  .import-button {
    position: absolute;
    right: 60px;
    top: 4px;
  }
}
</style>
